package com.itwk.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itwk.common.constant.PurchaseConstant;
import com.itwk.common.constant.PurchaseDetailConstant;
import com.itwk.common.exception.MergePurchaseException;
import com.itwk.common.utils.PageUtils;
import com.itwk.common.utils.Query;
import com.itwk.common.utils.R;
import com.itwk.gulimall.ware.dao.WmsPurchaseDao;
import com.itwk.gulimall.ware.entity.WmsPurchaseDetailEntity;
import com.itwk.gulimall.ware.entity.WmsPurchaseEntity;
import com.itwk.gulimall.ware.entity.WmsWareSkuEntity;
import com.itwk.gulimall.ware.feign.SkuInfoFeign;
import com.itwk.gulimall.ware.service.WmsPurchaseDetailService;
import com.itwk.gulimall.ware.service.WmsPurchaseService;
import com.itwk.gulimall.ware.service.WmsWareSkuService;
import com.itwk.gulimall.ware.vo.DonePurchaseDetailVo;
import com.itwk.gulimall.ware.vo.DonePurchaseVo;
import com.itwk.gulimall.ware.vo.PurchaseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wmsPurchaseService")
public class WmsPurchaseServiceImpl extends ServiceImpl<WmsPurchaseDao, WmsPurchaseEntity> implements WmsPurchaseService {
    @Autowired
   private  WmsPurchaseDetailService purchaseDetailService;
   @Autowired
    private WmsWareSkuService wareSkuService;//用于入库保存
    @Autowired
    private SkuInfoFeign skuInfoFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WmsPurchaseEntity> page = this.page(
                new Query<WmsPurchaseEntity>().getPage(params),
                new QueryWrapper<WmsPurchaseEntity>()
        );

        return new PageUtils(page);
    }

    //合并采购项目
    @Override
    public void mergePurchaseDetail(PurchaseVo purchaseVo) {
        //合并分为两种情况，如果选择了采购单即合并到指定采购单，否则创建新的采购单
        Long purchaseId = purchaseVo.getPurchaseId();
        //没有采购单，默认新建采购单
        if(null == purchaseId){
            WmsPurchaseEntity purchaseEntity = new WmsPurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(PurchaseDetailConstant.NEWING.getCode());
            purchaseEntity.setPriority(0);
            baseMapper.insert(purchaseEntity);
            purchaseId=purchaseEntity.getId();

        }else{
            //已有的采购合并前判断下状态是否可以被合并。
            WmsPurchaseEntity purchaseEntity = baseMapper.selectById(purchaseId);
            Integer status = purchaseEntity.getStatus();
            if(status==PurchaseConstant.RECEVIE.getCode()||status==PurchaseConstant.RECEVIED.getCode()||status==PurchaseConstant.SUCCESS.getCode()
                    ||status==PurchaseConstant.HASRROR.getCode() ){

                 throw  new MergePurchaseException("该采购单已分配采购中或已采购完成，不能合并！！");

            }
        }



        //合并采购项
          Long finalPurchaseId=purchaseId;  //lambda 参数必须是最终值们不能变化
        List<Long> items = purchaseVo.getItems();
        List<WmsPurchaseDetailEntity> collect =  items.stream().filter(item->{
            //判断采购项是否可以合并
            WmsPurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item);

            if(purchaseDetail.getStatus()==PurchaseDetailConstant.PURCHASEING.getCode()||purchaseDetail.getStatus()==PurchaseDetailConstant.SUCCESS.getCode()){
                return false;
            }
            return true;
        }).map(item -> {
                WmsPurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item);
                purchaseDetail.setPurchaseId(finalPurchaseId);
                purchaseDetail.setStatus(PurchaseDetailConstant.RECEVIE.getCode());  //设置状态
                return purchaseDetail;
            }).collect(Collectors.toList());

           if(collect==null||collect.size()<=0){

               throw new MergePurchaseException("所选采购项均在采购中或采购已完成，请核对！！");
           }

            purchaseDetailService.updateBatchById(collect);  //采购单完成合并

        WmsPurchaseEntity purchaseEntity = new WmsPurchaseEntity();   //保存采购单修改时间
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        baseMapper.updateById(purchaseEntity);

    }

    //合并采购项到采购单，查询可分配采购单   状态 0-新建，1-已分配，2-正在采购，3-采购完成，采购失败；
    @Override
    public PageUtils getUnReceivePurchase(Map<String, Object> params) {
        IPage<WmsPurchaseEntity> page = baseMapper.selectPage(
                new Query<WmsPurchaseEntity>().getPage(params),
                new QueryWrapper<WmsPurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Override    //采购人员领取采购单
    public void receivedPurchase(List<Long> purchaseIds) {
     //修改采购单状态
        for (Long purchaseId : purchaseIds) {
            WmsPurchaseEntity purchaseEntity = new WmsPurchaseEntity();
            purchaseEntity.setStatus(PurchaseConstant.RECEVIED.getCode());
            purchaseEntity.setId(purchaseId);
            baseMapper.updateById(purchaseEntity);

       //修改采购项的状态
            List<WmsPurchaseDetailEntity> purchaseDetails = purchaseDetailService.list(new QueryWrapper<WmsPurchaseDetailEntity>().eq("purchase_id", purchaseId));

            List<WmsPurchaseDetailEntity> collect = purchaseDetails.stream().map(purchaseDetail -> {

                purchaseDetail.setStatus(PurchaseDetailConstant.PURCHASEING.getCode());

                return purchaseDetail;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect);
        }
    }

    @Override   //完成采购业务
    public void donePurchase(DonePurchaseVo donePurchaseVo) {
          //完成采购单之前需要判断每个采购项目的完成状态，如果有采购项是失败的，此采购单为异常状态
        List<DonePurchaseDetailVo> items = donePurchaseVo.getItems();
        boolean hasError =false;
        for (DonePurchaseDetailVo item : items) { //如果采购项成功，保存采购项的状态，并且将采购入库，失败则设置失败状态，保存失败原因，但数据库没有设设计此字段，暂不实现
            if(item.getStatus()==PurchaseDetailConstant.SUCCESS.getCode()){
                //采购成功 ，保存状态并且入库
                WmsPurchaseDetailEntity purchaseDetailEntity = new WmsPurchaseDetailEntity();
                purchaseDetailEntity.setId(item.getItemId());
                purchaseDetailEntity.setStatus(item.getStatus());
                purchaseDetailService.updateById(purchaseDetailEntity);
                //采购数目入库,入库时保证同仓同sku ， 查寻采购项中的sku_id 和 采购数量， 另外需要判断两种情况如果采购项在仓库中本来没有其实为新增，则需要保存它的sku_name;
                WmsPurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item.getItemId());
                List<WmsWareSkuEntity> warskus = wareSkuService.list(new QueryWrapper<WmsWareSkuEntity>().eq("sku_id", purchaseDetail.getSkuId()).eq("ware_id", purchaseDetail.getWareId()));
                if(warskus==null ||warskus.size()<=0){
                    WmsWareSkuEntity wareSku = new WmsWareSkuEntity();
                    wareSku.setSkuId( purchaseDetail.getSkuId());
                    wareSku.setStock(purchaseDetail.getSkuNum());
                    wareSku.setWareId(purchaseDetail.getWareId());
                    //TODO 远程调用查询sku_name
                    try{   //为了防止调用服务设置名字异常回滚，捕捉异常，不处理
                        R r = skuInfoFeign.info(purchaseDetail.getSkuId());
                        if(r.getCode()==0){
                            Map<String, Object> skuInfo = (Map<String, Object>) r.get("skuInfo");
                            wareSku.setSkuName((String)skuInfo.get("skuName"));
                        }
                    }catch(Exception e){

                    }

                    wareSkuService.save(wareSku);
                }else{  //不是新增，修改库存值即可
                    WmsWareSkuEntity wareSku = warskus.get(0);
                    wareSku.setStock(wareSku.getStock()+purchaseDetail.getSkuNum());
                    wareSkuService.updateById(wareSku);
                }

            }else{//不满足条件，证明采购失败 ，将标记置为true；
                hasError =true;
                WmsPurchaseDetailEntity purchaseDetailEntity = new WmsPurchaseDetailEntity();
                purchaseDetailEntity.setId(item.getItemId());
                purchaseDetailEntity.setStatus(item.getStatus());
                purchaseDetailService.updateById(purchaseDetailEntity);

            }

    }

        //最后根据采购项是否全部成功，保存采购单的状态
        if(hasError){
            WmsPurchaseEntity purchaseEntity = new WmsPurchaseEntity();
            purchaseEntity.setId(donePurchaseVo.getId());
            purchaseEntity.setStatus(PurchaseConstant.HASRROR.getCode());
            baseMapper.updateById(purchaseEntity);
        }else{
            WmsPurchaseEntity purchaseEntity = new WmsPurchaseEntity();
            purchaseEntity.setId(donePurchaseVo.getId());
            purchaseEntity.setStatus(PurchaseConstant.SUCCESS.getCode());
            baseMapper.updateById(purchaseEntity);
        }

    }

}